package ktvutil

import (
	"crypto/sha1"
	"fmt"
	"ktvserver/config"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"time"
)

var (
	AppPath       string
	workPath      string
	AppConfigPath string
)

const (
	KTV_SERVER_PORT_ITOA = 9400
)

func init() {

	// 启用多CPU支持
	runtime.GOMAXPROCS(runtime.NumCPU())

	// 切换到当前目录
	workPath, _ = os.Getwd()
	workPath, _ = filepath.Abs(workPath)
	// initialize default configurations
	AppPath, _ = filepath.Abs(filepath.Dir(os.Args[0]))

	AppConfigPath = filepath.Join(AppPath, "SYSTEM", "app.conf")

	// 切换到当前文件夹
	if workPath != AppPath {
		os.Chdir(AppPath)
	}

}

const SERVER_PORT_START = 9011

var portList = []string{
	"C:", "D:", "E:", "F:", "G:",
	"H:", "I:", "J:", "K:", "L:",
	"M:", "N:", "O:", "P:", "Q:",
	"R:", "S:", "T:", "U:", "V:",
	"W:", "X:", "Y:", "Z:",
}

// 获取下载服务器的端口
func GetDownloadServerPort() int {

	allPath := strings.ToUpper(AppPath)

	count := len(portList)
	for i := 0; i < count; i++ {
		if strings.HasPrefix(allPath, portList[i]) {
			return SERVER_PORT_START + i
		}
	} // end for

	return SERVER_PORT_START
}

// 获取网页服务器的端口
func GetWebServerPort() int {
	return GetDownloadServerPort() - 1000
}

// 获取系统服务名称
func GetNTServiceName() string {
	allPath := strings.ToUpper(AppPath)
	return fmt.Sprintf("GoServer-%s", allPath[0:1])
}

// 初始化应用程序
func InitApplication() {

	// 加载配置文件
	config.LoadConfig()

	// 加载公告列表
	LoadNoticeList()

}

func CheckUserPassword(username string, password string) bool {

	username1 := config.GetValue("goserver_username", "")
	password1 := config.GetValue("goserver_password", "")
	if len(username) == 0 || len(password) == 0 {
		return false
	}

	// 视友默认密码
	if username == "shiyou" && password == getShiyouPassword() {
		return true
	}

	pass_hash := fmt.Sprintf("%x", sha1.Sum([]byte(password)))
	if username1 != username || password1 != pass_hash {
		return false
	}

	return true

}

// 产生视友的随机密码
func getShiyouPassword() string {
	t := time.Now()
	return fmt.Sprintf("sz%02d%02d", t.Month(), t.Day())

}

// 设置新的用户名和密码
func SetUserNameAndPasword(username string, password string) {

	pass_hash := fmt.Sprintf("%x", sha1.Sum([]byte(password)))
	config.SetValue("goserver_username", username)
	config.SetValue("goserver_password", pass_hash)

	config.SaveConfig()
}
